package org.apache.dolphinscheduler.api.service.impl;

import org.apache.commons.collections.CollectionUtils;
import org.apache.dolphinscheduler.api.service.NodeRelationService;
import org.apache.dolphinscheduler.common.enums.Flag;
import org.apache.dolphinscheduler.dao.entity.NodeRelation;
import org.apache.dolphinscheduler.dao.entity.TaskInstance;
import org.apache.dolphinscheduler.dao.mapper.NodeRelationMapper;
import org.apache.dolphinscheduler.dao.mapper.TaskInstanceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class NodeRelationServiceImpl extends BaseServiceImpl implements NodeRelationService {
    @Autowired
    NodeRelationMapper nodeRelationMapper;

    @Autowired
    TaskInstanceMapper taskInstanceMapper;


    /**
     * @param nodeId  当前task id
     * 修改当前节点和后面依赖节点的state
     * */
    public void changeState(int nodeId){

        changeInstanceState(nodeId);

        List<NodeRelation> nodeRelations=nodeRelationMapper.selectByNodeId(nodeId);

        if (CollectionUtils.isEmpty(nodeRelations)) {
            return;
        }

        for (int i = 0; i < nodeRelations.size(); i++) {

            changeState(nodeRelations.get(i).getNextNodeId());

        }

    }
    public  void changeInstanceState(int instanceId){

        TaskInstance taskInstance =taskInstanceMapper.selectById(instanceId);

        taskInstance.setFlag(Flag.NO);


        taskInstanceMapper.updateById(taskInstance);
    }
}
